package org.ws.task.example.batch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ws.task.item.ItemLeaderProvider;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@RestController
public class BatchController {

    @Autowired
    private Job uuidJob;

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private ItemLeaderProvider<String> uuidItemProvider;

    @GetMapping("/run")
    public void run(){

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(()->{
            JobParameters jobParameters = new JobParametersBuilder()
                    .addLong("startTime",System.currentTimeMillis())
                    .toJobParameters();
            try {
                jobLauncher.run(uuidJob, jobParameters);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        });
    }

    @GetMapping("/reset")
    public void reset(){
        ((FileLineItemLeaderProvider)uuidItemProvider).reset();
    }

}
